//
//  ZCScanVC.m
//  zctx
//
//  Created by ZhengDarren on 15/9/28.
//  Copyright © 2015年 sanliang. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "ZCScanVC.h"
#import "QRUtil.h"
#import "QRView.h"

#import "ZCSearchVC.h"
@interface ZCScanVC ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>

@property (nonatomic) AVCaptureSession *captureSession;
@property (nonatomic) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic) AVCaptureMetadataOutput *captureMetadataOutput;
@property (nonatomic) BOOL lastResult;

@property (nonatomic, strong) QRView *qrView;
@end

@implementation ZCScanVC

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    if (![_captureSession isRunning]) {
        
        [self startReading];
    }
    _lastResult = YES;
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [_videoPreviewLayer removeFromSuperlayer];
    [_captureSession stopRunning];
    _lastResult = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    self.view.backgroundColor = [UIColor clearColor];
    
    [self.navigationItem setTitle:@"扫一扫"];
    [self startReading];
    [self.view addSubview:self.qrView];
    [self updateLayout];
    
}



- (BOOL)startReading {
    _lastResult = YES;
    NSError *error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    _captureSession = [[AVCaptureSession alloc] init];
    // Set the input device on the capture session.
    [_captureSession addInput:input];
    
    _captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_captureSession addOutput:_captureMetadataOutput];
    
    // Create a new serial dispatch queue.
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [_captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [_captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, nil]];
    
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:self.view.layer.bounds];
//    [self.view.layer addSublayer:_videoPreviewLayer];
    
    [self.view.layer insertSublayer:_videoPreviewLayer atIndex:0];
    
    [_captureSession startRunning];
    
    return YES;
}


-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects
      fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *result;
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            result = metadataObj.stringValue;
        } else {
            result = metadataObj.stringValue;
    
        }
         NSLog(@"条形码 = %@",result);
        [self requestScanList:result];
    }
}

#pragma mark - request 扫一扫条形码请求

- (void)requestScanList:(NSString *)result {
    
    [self stopReading];
    if (!_lastResult) {
        return;
    }
    _lastResult = NO;

    [NetworkManager requestProductGetInfoByBarcodeWithMid:UserModel.mid barcode:result success:^(NSDictionary *dictResponse) {
      
        NSDictionary *array = (NSDictionary *)[dictResponse objectForKey:@"content"];

        if (array.count >0) {
            ZCSearchVC *vc = [[ZCSearchVC alloc]init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.barcodeDictionary = [array copy];
            theAppdelegate.tabbarIndex = @"1";
            [self.navigationController pushViewController:vc animated:NO];
        }else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"此条码暂时没有数据!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alertView show];
            
        }
        _lastResult = YES;
    } failure:^(NSError *error) {

    }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        theAppdelegate.tbc.selectedIndex= 0 ;
}

- (void)updateLayout {
    
    _qrView.center = CGPointMake([QRUtil screenBounds].size.width / 2, [QRUtil screenBounds].size.height / 2);
    
    //修正扫描区域
    CGFloat screenHeight = self.view.frame.size.height;
    CGFloat screenWidth = self.view.frame.size.width;
    CGRect cropRect = CGRectMake((screenWidth - self.qrView.transparentArea.width) / 2,
                                 (screenHeight - self.qrView.transparentArea.height) / 2,
                                 self.qrView.transparentArea.width,
                                 self.qrView.transparentArea.height);
    
    [_captureMetadataOutput setRectOfInterest:CGRectMake(cropRect.origin.y / screenHeight,
                                                         cropRect.origin.x / screenWidth,
                                                         cropRect.size.height / screenHeight,
                                                         cropRect.size.width / screenWidth)];
}

-(QRView *)qrView {
    
    if (!_qrView) {
        
        CGRect screenRect = [QRUtil screenBounds];
        _qrView = [[QRView alloc] initWithFrame:screenRect];
        _qrView.transparentArea = CGSizeMake(250, 200);
        
        _qrView.backgroundColor = [UIColor clearColor];
    }
    return _qrView;
}



@end
